import HotkeyRegister, { HotkeyHandlerParams } from './HotkeyRegister'
import { HotkeyType } from './useHotkey'
import { Keys } from './types'
import { isElEditable } from '@/utils'
import { getWidgetSelection } from './utils'
import { moveCheckGroupOption } from '../../../widgets/checkbox-group/utils'

/** 移动像素 */
const MOVE_STEP = 4

/** 移动像素 - Control 键 */
const MOVE_STEP_CTRL = 10

/** 跟进按键获取移动距离 */
function getMoving(e: KeyboardEvent) {
  const { key, ctrlKey, metaKey } = e

  /** 移动距离 x */
  let x = 0
  /** 移动距离 y */
  let y = 0

  /** 移动步进 */
  const step = ctrlKey || metaKey ? MOVE_STEP_CTRL : MOVE_STEP

  if (key === Keys.ArrowLeft) {
    x = -step
  } else if (key === Keys.ArrowRight) {
    x = step
  }

  if (key === Keys.ArrowUp) {
    y = -step
  } else if (key === Keys.ArrowDown) {
    y = step
  }

  return { x, y }
}

/** 移动控件 */
function moveWidget({ e, viewer }: HotkeyHandlerParams) {
  if (isElEditable(e.target)) return

  const list = getWidgetSelection(viewer).filter(widget => !widget.isFixed)

  if (!list.length) return

  e.preventDefault()

  list.forEach(widget => {
    const { x, y } = getMoving(e)

    const { activeOption } = widget

    // 单复选框子选项移动
    if (list.length === 1 && activeOption) {
      moveCheckGroupOption(widget, activeOption, x, y)

      return
    }

    widget.move(x, y)
  })
}

/** 控件移动 */
export default function useWidgetMove(register: HotkeyRegister) {
  /** 移动控件 上 */
  register.add({
    keys: [Keys.ArrowUp, Keys.ArrowDown, Keys.ArrowLeft, Keys.ArrowRight],
    type: HotkeyType.KEYDOWN,
    handler: moveWidget
  })
}
